/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.aal.controller;

import com.aal.entity.Account;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author HUNG
 */
public class AccountController extends BaseController<Account> {

    @Override
    public List<Account> getAll() throws Exception {
        open();
        List<Account> list = new ArrayList<Account>();
        ResultSet rs = select("SELECT * FROM Account", null);
        while (rs.next()) {
            list.add(new Account(rs.getString("Username"), rs.getString("Password"), rs.getString("SecretQuestion"), rs.getString("SecretAnswer"), rs.getString("Role"), rs.getString("Discount")));
        }
        close();
        return list;
    }

    @Override
    public Account getById(Account t) throws Exception {
        open();
        Account account = null;
        ResultSet rs = select("SELECT * FROM Account", null);
        while (rs.next()) {
            account = new Account(rs.getString("Username"), rs.getString("Password"), rs.getString("SecretQuestion"), rs.getString("SecretAnswer"), rs.getString("Role"), rs.getString("Discount"));
        }
        close();
        return account;
    }

    @Override
    public int add(Account t) throws Exception {
        open();
        String[] param = {t.getUsername(), t.getPassword(), t.getSecretQuestion(), t.getSecretAnswer(), t.getRole(), t.getDiscount()};
        int run = run("INSERT INTO Account(Username, Password, SecretQuestion, SecretAnswer, Role, Discount) VALUES (?, ?, ?, ?, ?, ?)", param);
        close();
        return run;
    }

    @Override
    public int update(Account t) throws Exception {
        open();
        String[] param = {t.getPassword(), t.getSecretQuestion(), t.getSecretAnswer(), t.getRole(), t.getDiscount(), t.getUsername()};
        int run = run("UPDATE Account SET Password = ?, SecretQuestion = ?, SecretAnswer = ?, Role = ?, Discount = ? WHERE Username = ?", param);
        close();
        return run;
    }

    @Override
    public int delete(Account t) throws Exception {
        open();
        String[] param = {t.getUsername()};
        int run = run("DELETE FROM Account WHERE Username = ?", param);
        close();
        return run;
    }

    /**
     *
     * Ham test
     */
    public static void main(String[] args) {
        AccountController ac = new AccountController();
        try {
            Account acc = new Account("testU", "slkdjflk", "testSec", "testA", "admin", "500");
            int add = ac.update(acc);
            System.out.println(add);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
